//
//  PywForgetResetPwdViewController.m
//  PywSdk
//
//  Created by smallwave on 16/8/4.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywForgetResetPwdViewController.h"
#import "PywMasonry.h"
#import "PywTextFieldView.h"
#import "UIButton+Pyw.h"
#import "UILabel+Pyw.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywSetPwdApi.h"
#import "ApiClientConst.h"
#import "PywSdk+login.h"
#import "PywLoginView.h"
#import "PywLogoutManger.h"
#import "PywUser.h"
#import "PywPassportUtils.h"
#import "PywPlatformMain.h"
#import "MutableDictionary.h"
#import "PywRSAUtil.h"

#define kPasswordMinLenght 6
#define kPasswordMaxLenght 12

@interface PywForgetResetPwdViewController ()

@property (nonatomic, strong) UILabel           *propmtLabel;           // 描述信息
@property (nonatomic, strong) PywTextFieldView  *resetPwdView;          // 重置密码输入框
@property (nonatomic, strong) UIButton          *resetAndLoginBtn;      // 重置密码并登陆按钮
@property (nonatomic, strong) UILabel           *noticeLabel;           // 温馨提示:修改成功后,请用手机号码和手机密码登录


@property (nonatomic, copy) NSString            *phoneNumber;           // 手机号码
@property (nonatomic, copy) NSString            *smsCode;               // 短信验证码
@property (nonatomic, copy) NSString            *smsType;               // 获取验证码场景类型
@property (nonatomic, copy) NSString            *account_num;           // 游戏账号数量
@property (nonatomic, copy) NSString            *is_check_smscode;      // 校验密码已经通过的标记位

@property (nonatomic, strong) PywSetPwdApi      *resetPwdApi;           // 重置密码请求

@end

@implementation PywForgetResetPwdViewController
KeyBoardHelper(85)

#pragma mark - Init
- (instancetype)initWithPhoneNumber:(NSString *)phoneNumber
                            smsCode:(NSString *)smsCode
                            smsType:(NSString *)smsType
                      AccountNumber:(NSString *)account_num
                     IsCheckSmsCode:(NSString *)is_check_smscode
{
    self = [super init];
    if (self) {
        self.phoneNumber = phoneNumber;
        self.smsCode = smsCode;
        self.smsType = smsType;
        self.account_num = account_num;
        self.is_check_smscode = is_check_smscode;
    }
    return self;
}

#pragma mark - Lift Cycle Method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUp];
}

#pragma mark - prepareUI
- (void)setUp{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"重置密码";
    self.navigationItem.rightBarButtonItem = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addSubviewsAndLayoutSubviews];
}
- (void)addSubviewsAndLayoutSubviews{
    
    [self.view addSubview:self.propmtLabel];
    [self.view addSubview:self.resetPwdView];
    [self.view addSubview:self.resetAndLoginBtn];
    [self.view addSubview:self.noticeLabel];
    
    __weak typeof(self) wSelf = self;
    [self.propmtLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.view.mas_top).offset(80);
        make.width.equalTo(wSelf.view.mas_width).multipliedBy(0.85);
    }];
    
    [self.resetPwdView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.propmtLabel.mas_bottom).offset(20);
        make.width.equalTo(wSelf.propmtLabel.mas_width);
        make.height.equalTo(@40);
    }];
    
    [self.resetAndLoginBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.resetPwdView.mas_bottom).offset(40);
        make.width.height.equalTo(wSelf.resetPwdView);
    }];
    
    [self.noticeLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.equalTo(wSelf.view.mas_centerX);
        make.top.equalTo(wSelf.resetAndLoginBtn.mas_bottom).offset(20);
    }];
}

#pragma mark - Action
- (void)resetAndLoginBtnAction{
    [self.view endEditing:YES];
    
    if (self.resetPwdView.text.length < kPasswordMinLenght) {
        
        [PywMBProgressHUD showError:@"密码不能低于6位" toView:self.navigationController.view];
    } else if (self.resetPwdView.text.length > kPasswordMaxLenght){
        
        [PywMBProgressHUD showError:@"密码不能超出12位" toView:self.navigationController.view];
    } else {
        [self.resetPwdApi requestSetPwdWithParams:[self requestSetPwdParams] success:^(NSString *status, id anyObjct) {
            
            [self resetPwdSuccessWithDismissContorllerAndLoginMainView];
        } fail:^(NSError *error) {
            
        }];
    }
}
/**
 *  重置密码成功后，关闭控制器。注销登录后调出主登录界面
 */
- (void)resetPwdSuccessWithDismissContorllerAndLoginMainView{
    if (![PywSdk manger].isLogined) {  // 未登录过
        // 重置成功，关闭当前控制器并发送通知
        [self dismissViewControllerAnimated:YES completion:^{
            
            MutableDictionary *param = [[MutableDictionary alloc] init];
            NSString *password = [PywRSAUtil encryptString:self.resetPwdView.text];
            [param setObject:self.phoneNumber forKey:@"passport"];
            [param setObject:password forKey:@"password"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:DidRegisterSuccess object:param];
        }];
    } else {
        // 重置成功，关闭当前控制器并调用主登录界面
        // 清空本地当前账号的密码
        PywUser *user = [[PywUser alloc] init];
        user.passport = [PywPlatformMain sharedPlatformMain].userName;
        user.password = @"";
        [PywPassportUtils savePassport:user];
        // 注销后,关闭控制器并调出主登录界面
        [[PywLogoutManger manger] clearLogin];
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            [[PywSdk manger] login];
        }];  
    }
}

/**
 *  设置登录密码  传入参数
 */
- (MutableDictionary *)requestSetPwdParams{
    NSString *passport = [self.phoneNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *password = [self.resetPwdView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *smsCode = [self.smsCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *smsType = [self.smsType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *is_check_smscode = [self.is_check_smscode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    MutableDictionary *params = [[MutableDictionary alloc] init];
    [params setObject:passport forKey:@"passport"];
    [params setObject:password forKey:@"password"];
    [params setObject:smsCode forKey:@"smscode"];
    [params setObject:smsType forKey:@"smstype"];
    [params setObject:is_check_smscode forKey:@"is_check_smscode"];
    return params;
}

#pragma mark - Setter & Getter
- (UILabel *)propmtLabel{
    if (!_propmtLabel) {
        _propmtLabel = [UILabel labelWithText:nil
                                textAlignment:NSTextAlignmentLeft
                                     fontSize:12
                                    textColor:[UIColor blackColor]];

        NSString *propmtStr = [NSString stringWithFormat:@"登录手机:%@(已绑定%@个游戏账号)",self.phoneNumber,self.account_num];
        NSMutableAttributedString *propmtMessage = [[NSMutableAttributedString alloc] initWithString:propmtStr];
        [propmtMessage addAttribute:NSForegroundColorAttributeName value:RGB(252, 177, 14, 1) range:NSMakeRange(5, self.phoneNumber.length)];
        
        _propmtLabel.attributedText = propmtMessage;
    }
    return _propmtLabel;
}
- (PywTextFieldView *)resetPwdView{
    if (!_resetPwdView) {
        _resetPwdView = [PywTextFieldView passwordTextFieldWithLeftImg:@"icon_password_normal"
                                                       TextPlaceholder:@"请输入登录密码（限6-12字符）"
                                                       ButtonNormalImg:@"icon_visible_normal"
                                                     ButtonSelectedImg:@"icon_visible_disabled"];
        [_resetPwdView setAccessibilityId:@"fogotpwsd_pwsd"];
    }
    return _resetPwdView;
}
- (UIButton *)resetAndLoginBtn{
    if (!_resetAndLoginBtn) {
        _resetAndLoginBtn = [UIButton buttonWithBackgroundColor:RGB(238, 151, 15, 1)
                                                      cornerRadius:20
                                                        titleColor:[UIColor whiteColor]
                                                titleLabelFontSize:18
                                                             title:@"重置密码并登录"];
        [_resetAndLoginBtn addTarget:self action:@selector(resetAndLoginBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_resetAndLoginBtn setAccessibilityIdentifier:@"fogotpwsd_login"];
    }
    return _resetAndLoginBtn;
}

- (UILabel *)noticeLabel
{
    if (!_noticeLabel) {
        _noticeLabel = [UILabel labelWithText:@"温馨提示:修改成功后,请用手机号码和手机密码登录"
                                textAlignment:NSTextAlignmentLeft
                                     fontSize:12
                                    textColor:[UIColor grayColor]];
    }
    return _noticeLabel;
}

- (PywSetPwdApi *)resetPwdApi{
    if (!_resetPwdApi) {
        _resetPwdApi = [PywSetPwdApi manager];
    }
    return _resetPwdApi;
}

@end
